<template>
	<view>
		<cu-custom bgColor="bg-informatic-brown" isBack>
			<block slot="backText">返回</block>
			<block slot="content">{{lecture.Name}}</block>
		</cu-custom>
		<view class="bg-white padding">
			<view>
				<text class="text-xl text-bold">讲座：{{lecture.Name}}</text>
			</view>
			<view class="margin-top flex justify-between align-center">
				<text>{{lecture.SignUpBegin}} - {{lecture.SignUpEnd}}</text>
				<text class="cu-tag bg-blue round">{{state}}</text>
			</view>
		</view>
		<view class="cu-list menu sm-border" style="margin-top: 2rpx;">
			<view class="cu-item">
				<view class="content">
					<text class="cuIcon-location line-brown"></text>
					<text class="">{{lecture.Address}}</text>
				</view>
			</view>
			<view class="cu-item">
				<view class="content">
					<text class="cuIcon-people line-mauve"></text>
					<text class="">{{lecture.Hoster}}</text>
				</view>
			</view>
			<view class="cu-item">
				<view class="content">
					<text class="cuIcon-edit line-orange"></text>
					<text class="">报名情况：{{lecture.SignUpLimit ? signUpCount + '/' + lecture.SignUpLimit + '人' : "无限制"}}</text>
				</view>
			</view>
			<view class="cu-item" v-if="totalMissed != 0">
				<view class="content">
					<text class="cuIcon-roundclose line-red"></text>
					<text class="">本学期报名但未签到次数:{{totalMissed}}</text>
				</view>
			</view>
		</view>
		<view class="cu-list menu sm-border">
			<view class="cu-item">
				<view class="content">
					<text class="text-lg">子讲座列表</text>
				</view>
			</view>
			<block v-for="subLecture in subLectures" :key="subLecture.ID">
				<view class="cu-item" :class="{logo: subLecture.State == '已签到'}" @click="show(subLecture.ID)">
					<view class="content">
						<text class="cuIcon-btn text-green"></text>
						<text>{{subLecture.Name}}</text>
					</view>
					<view class="action">
						<button v-if="false" class="cu-btn line-green margin-lr" @click="toSignUp(subLecture.ID)">
							签到
						</button>
					</view>
				</view>
				<view class="padding solid-top solid-bottom bg-white" v-show="showDetail === subLecture.ID">
					<text class="cuIcon-info"></text>
					<text>状态：{{subLecture.State}}</text>
					<br />
					<text class="cuIcon-people"></text>
					<text>汇报人：{{subLecture.Hoster}}</text>
					<br />
					<text class="cuIcon-location"></text>
					<text>地点：{{subLecture.Address}}</text>
					<br />
					<text class="cuIcon-time"></text>
					<text>活动开始时间：{{subLecture.BeginOn}}</text>
					<br />
					<text class="cuIcon-timefill"></text>
					<text>活动结束时间：{{subLecture.EndOn}}</text>
					<!-- <br />
					<text class="cuIcon-timefill" v-if="showSignInState"></text>
					<text v-if="showSignInState">签到情况：{{subLecture.signInState}}</text> -->
				</view>
			</block>
		</view>
		<view class="cu-list menu">
			<view class="cu-item">
				<view class="content">
					<text class="text-lg">讲座介绍</text>
				</view>
			</view>
			<!-- <view class="bg-white padding-lr padding-tb-xs" style="text-indent: 1em;" > -->
			<view class="bg-white padding-lr padding-tb-xs">
				<text selectable user-select v-html="lecture.Content ? lecture.Content : '暂无简介'"></text>
			</view>
		</view>
		<view class="cu-bar foot bg-white">
			<view class="flex-sub text-center">
				<text class="text-lg text-bold" :class="{'text-green':isSignedUp}">{{isSignedUp?"已报名":"未报名"}}</text>
			</view>
			<view class="flex-treble flex justify-end padding-lr">
				<button class="bg-cyan cu-btn round lg" v-if="conflicts.length">
					<text class="padding-lr-xl" @click="showConflict">时间冲突</text>
				</button>
				<button class="bg-cyan cu-btn round lg" v-else :disabled="signUpDisable">
					<text class="padding-lr-xl" @click="checkSignUpState">{{btnText}}</text>
				</button>
			</view>
		</view>
		<view style="height: 50px;"></view>
		<view class="cu-modal" :class="showModal ? 'show' : ''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">冲突讲座列表</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-xl">
					<view v-for="(ac, index1) in conflicts" :key="index1">
						<view class="bg-blue light text-left padding solid" v-for="(a, index2) in ac.Conflicts" :key="index2">
							<text>讲座名：{{a.Name}}</text><br />
							<text>开始时间：{{a.BeginOn}}</text><br />
							<text>结束时间：{{a.EndOn}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	let app = require("@/config");
	export default {
		data() {
			return {
				showModal: false,
				showDetail: "",
				lecture: {},
				conflicts: {},
				subLectures: [],
				isSignedUp: false,
				lectureId: "",
				state: "未知",
				showSignInState: false,
				signInState: "未知",
				totalDelay: 0,
				totalMissed: 0,
				btnText: "我要报名",
				timer: -1,
				leftTime: 0,
				signUpDisable: false,
				signUpCount: 0,
				countDownTimer: -1
			}
		},
		onLoad(e) {
			this.getSubLectures(e.id);
			this.lectureId = e.id;
		},
		onBackPress() {
			clearInterval(this.timer);
			clearInterval(this.countDownTimer)
		},
		onHide() {
			clearInterval(this.timer);
			clearInterval(this.countDownTimer)
		},
		onUnload() {
			clearInterval(this.timer);
			clearInterval(this.countDownTimer)
		},
		methods: {
			// 打开冲突提示模态框
			showConflict() {
				this.showModal = true;
			},
			// 展开子讲座详细信息
			show(id) {
				this.showDetail = id === this.showDetail ? "" : id;
			},
			changeButton() {
				if (this.isSignedUp) {
					this.btnText = "取消报名";
				} else {
					let now = new Date();
					if((new Date(this.lecture.SignUpBegin) - now) > 0){
						let totalDiffSecond = (new Date(this.lecture.SignUpBegin) - now)/1000;
						let DiffHour = Math.floor(totalDiffSecond / 3600);
						let DiffMinute = Math.floor((totalDiffSecond % 3600) / 60);
						let DiffSecond = Math.floor((totalDiffSecond % 3600 % 60));
						this.btnText = `${DiffHour}时${DiffMinute}分${DiffSecond}秒后\n开始报名`
					}
					else {
						if (this.totalDelay === 0) {
							this.btnText = "我要报名";
						} else {
							this.btnText = "我要报名(罚时" + this.leftTime + "秒)";
						}
					}
				}
			},
			// 获取父讲座信息与子讲座列表
			getSubLectures(id) {
				uni.post("/api/activity/GetUserActivityCategory", {
					id
				}, msg => {
					if (msg.success) {
						this.lecture = msg.data;
						this.subLectures = msg.activities;
						this.signUpCount = msg.signUpCount;
						this.isSignedUp = msg.isSignUp;
						if (!msg.isSignUp) {
							this.conflicts = msg.conflicts;
						}
						this.leftTime = this.totalDelay = msg.delay.total;
						this.totalMissed = msg.delay.miss.length;
						this.calcState();
						this.subLectures.reverse();
						this.subLectures.reverse();
					} else {
						uni.showToast({
							title: msg.msg,
							icon: "none"
						})
					}
				});
			},
			getSubLectureDetail(id) {
				uni.post("/api/activity/GetUserActivity", {
					id
				}, msg => {
					if (msg.success) {
						for (let i = 0; i < this.subLectures.length; i++) {
							if (this.subLectures[i].ID === id) {
								this.subLectures[i] = msg.data;
								if (msg.isSignIn) {
									this.$set(this.subLectures[i], "signInState", "已签到");
								} else {
									this.$set(this.subLectures[i], "signInState", "未签到");
								}
								break;
							}
						}
					} else {
						uni.showToast({
							title: msg.msg,
							icon: "none"
						})
					}
				});
			},
			// 计算父讲座状态
			calcState(isLoop) {
				let time = new Date();
				if (time < new Date(this.lecture.SignUpBegin)) {
					this.state = "未开始";
					this.signUpDisable = true;
					if(!isLoop) this.countDownTimer = setInterval(() => {this.calcState(true)} ,1000)
				} else if (time < new Date(this.lecture.SignUpEnd)) {
					this.state = "报名中";
					this.signUpDisable = false;
					clearInterval(this.countDownTimer)
				} else if (time > new Date(this.lecture.SignUpEnd)) {
					this.state = "预约结束";
					this.signUpDisable = true;
					clearInterval(this.countDownTimer)
				}
				this.changeButton();
			},
			toDetail(id) {
				uni.navigateTo({
					url: `./detail?id=${id}`
				});
			},
			toSignIn(id) {
				// 已经在App.vue页面中判断此问题了
				// if (!app.userInfo.isLogined) {
				// 	uni.showModal({
				// 		title: "用户未登录",
				// 		content: "请先登录。",
				// 		showCancel: false,
				// 		success: () => {
				// 			uni.navigateTo({
				// 				url: `../profile/profile`
				// 			});
				// 		}
				// 	});
				// 	return;
				// }
				if (!app.userInfo.email || !app.userInfo.mobile) {
					uni.showModal({
						title: "补全签到信息",
						content: "您没有填写手机号或者邮箱，请先填写后再签到。",
						showCancel: false,
						success: () => {
							uni.navigateTo({
								url: `../userInfo/userInfo`
							});
						}
					});
					return;
				}
				uni.navigateTo({
					url: `../signIn/signIn?id=${id}`
				});
			},
			// checkSignInState(id) {
			// 	let time = new Date();
			// 	if (time < new Date(this.lecture.BeginOn)) {
			// 		uni.showToast({
			// 			title: "签到未开始",
			// 			icon: "none"
			// 		});
			// 	} else if (time > new Date(this.lecture.EndOn)) {
			// 		uni.showToast({
			// 			title: "签到已结束",
			// 			icon: "none"
			// 		});
			// 	} else {
			// 		this.toSignIn(id);
			// 	}
			// },
			checkSignUpState() {
				let time = new Date();
				if (time < new Date(this.lecture.SignUpBegin)) {
					uni.showToast({
						title: "报名未开始",
						icon: "none"
					})
				} else if (time >= new Date(this.lecture.SignUpEnd)) {
					uni.showToast({
						title: "报名已结束",
						icon: "none"
					})
				} else {
					if (!this.isSignedUp) {
						this.signUpDisable = true;
						clearInterval(this.timer);
						if(this.leftTime > 0) {
							this.timer = setInterval(() => {
								if (--this.leftTime < 0) {
									clearInterval(this.timer);
									this.SignUp(0);
									this.leftTime = this.totalDelay;
								} else {
									this.changeButton();
								}
							}, 1000);
						} else {
							this.SignUp(0);
						}
					} else {
						uni.showModal({
							title: "取消报名",
							content: "确实要取消报名吗？",
							success: (res) => {
								if(res.confirm){
									this.SignUp(999);
								}
							}
						})
					}
				}
			},
			/* 报名函数 */
			SignUp(state) {
				// 999 - 取消报名
				// 0 - 报名
				this.signUpDisable = true;
				uni.post("/api/activity/SignUp", {
					state,
					id: this.lectureId
				}, msg => {
					this.signUpDisable = false;
					if (msg.success) {
						this.getSubLectures(this.lectureId);
						if (!this.isSignedUp) {
							uni.showToast({
								title: "报名成功"
							});
							this.isSignedUp = true;
						} else {
							uni.showToast({
								title: "取消报名成功"
							});
							this.isSignedUp = false;
						}
						this.changeButton();
					} else {
						let title = "";
						if (state === 999) {
							title = "取消报名失败";
						} else if (state === 0) {
							title = "报名失败";
						}
						uni.showModal({
							title: title,
							content: msg.msg
						})
					}
				});
			},
			hideModal() {
				this.showModal = false;
			},
			dateFormat(fmt, date) {
				if(date instanceof Date){
					
				}else{
					date = new Date(date);
				}
				
			    let ret;
			    const opt = {
			        "Y+": date.getFullYear().toString(),        // 年
			        "m+": (date.getMonth() + 1).toString(),     // 月
			        "d+": date.getDate().toString(),            // 日
			        "H+": date.getHours().toString(),           // 时
			        "M+": date.getMinutes().toString(),         // 分
			        "S+": date.getSeconds().toString()          // 秒
			        // 有其他格式化字符需求可以继续添加，必须转化成字符串
			    };
			    for (let k in opt) {
			        ret = new RegExp("(" + k + ")").exec(fmt);
			        if (ret) {
			            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
			        };
			    };
			    return fmt;
			}
		}
	}
</script>

<style>
	.logo {
		background-image: url('../../static/角标-已签到.png');
		background-repeat: no-repeat;
		background-size: 15%;
		background-position: 95% 50%;
	}
</style>
